<?php

namespace App\Filament\Resources\BorrowRecordResource\Pages;

use App\Filament\Resources\BorrowRecordResource;
use App\Models\Member;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

class CreateBorrowRecord extends CreateRecord
{
    protected static string $resource = BorrowRecordResource::class;


    protected function mutateFormDataBeforeCreate(array $data): array
    {
        if (Member::find($data['member_id'])->hasBorrowBook($data['book_id'])) {
            Notification::make()
                ->danger()
                ->title('录入失败')
                ->body('用户正在借阅中，无法再次借阅。')
                ->send();
            $this->halt();
        }
        $data['borrow_date'] = Carbon::now();
        return $data;
    }

    protected function afterCreate(): void
    {
        // Runs after the form fields are saved to the database.
        $this->getRecord()->book->decrement('quantity', 1);
    }

}
